<template>
  <div class="one-wrap">
    <step />
    <el-row class="item-container">
      <div class="title-wrap">
        <svg-icon icon-class="required" class-name="custom-class" />
        <div class="title">名称：</div>
      </div>
      <el-input v-model="info.package_name" type="text" placeholder="请输入名称" class="input-container" />
    </el-row>
    <!-- <el-row class="item-container">
      <div class="title">简介：</div>
      <el-input v-model="info.package_intro" type="textarea" placeholder="请输入简介" class="textarea-container" />
    </el-row> -->
    <el-row class="item-container">
      <div class="title-wrap">
        <svg-icon icon-class="required" class-name="custom-class" />
        <div class="title">封面图片：</div>
      </div>
      <cover :cover="info.package_list_pic" :ratio="coverRatio" @cover="handleCoverChange" />
    </el-row>
    <el-row v-show="type !== 'scenic'" class="item-container">
      <div class="title-wrap">
        <svg-icon icon-class="required" class-name="custom-class" />
        <div class="title">轮播图片：</div>
      </div>
      <carousel :carousel="info.package_pics" :ratio="ratio" @carousel="handleChangeCarousel" />
    </el-row>
    <el-row class="item-container">
      <div class="title-wrap">
        <svg-icon icon-class="required" class-name="custom-class" />
        <div class="title">套餐价：</div>
      </div>
      <el-input v-model="info.package_price" type="text" placeholder="请输入价格" class="input-container" />
    </el-row>
    <el-row class="item-container">
      <div class="title">市场价：</div>
      <el-input v-model="info.market_price" type="text" placeholder="请输入价格" class="input-container" />
    </el-row>
    <el-row v-show="roles[0] === 'hotel' || roles[0] === 'scenic'" class="item-container">
      <div class="title">默认库存：</div>
      <el-input v-model="info.stock_quantity" type="text" placeholder="请输入库存" class="input-container" />
    </el-row>
    <el-row class="item-container">
      <div class="title">排序：</div>
      <el-tooltip class="item" effect="dark" content="0 ~ 999数字越小排序越靠前" placement="top-start">
        <el-input v-model="info.seller_sort" type="text" placeholder="请输入排序（0 ~ 999数字越小排序越靠前）" class="input-container" />
      </el-tooltip>
    </el-row>
    <el-row class="item-container">
      <div class="title-wrap">
        <div class="title">标签：</div>
      </div>
      <el-select v-model="info.tag_id" placeholder="请选择">
        <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.tag_name"
          :value="item.tag_name"
        />
      </el-select>
      <el-button type="primary" class="management-btn" @click="putawayDialog=true">管理</el-button>
    </el-row>
    <!-- <el-row class="item-container">
      <div class="title">备注：</div>
      <el-input v-model="info.desc" type="textarea" placeholder="请输入排序" class="textarea-container" />
    </el-row> -->
    <el-button type="primary" @click="handleNext">下一步</el-button>
    <el-dialog
      :visible.sync="putawayDialog"
      :append-to-body="true"
      title="标签管理"
      width="30%"
      center
    >
      <el-row>
        <el-button type="primary" style="margin-bottom:10px;" class="management-btn" @click="handleAddTag">新增</el-button>
        <el-button type="primary" style="margin-bottom:10px;margin-left: 10px" class="management-btn" @click="handleDeleteAll">批量删除</el-button>
        <el-table ref="multipleTable" :data="tableData" border tooltip-effect="dark" style="width: 100%" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" />
          <el-table-column prop="" label="名称" min-width="200">
            <template slot-scope="scope">
              <template v-if="scope.row.edit">
                <el-input v-model="scope.row.tag_name" style="margin-right:10px;width: 100px;" class="edit-input" size="small" />
                <el-button class="cancel-btn" size="small" icon="el-icon-refresh" type="warning" @click="cancelEdit(scope)">取消</el-button>
              </template>
              <div v-else @dblclick="scope.row.edit=true">{{ scope.row.tag_name }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="seller_sort" label="操作" min-width="150">
            <template slot-scope="scope">
              <el-button v-if="scope.row.edit" type="success" icon="el-icon-circle-check-outline" style="margin-bottom: 15px" class="btn" @click="confirmEdit(scope.row)">确认</el-button>
              <el-button v-else type="primary" icon="el-icon-edit" style="margin-bottom: 15px" class="btn" @click="scope.row.edit=!scope.row.edit">编辑</el-button>
              <el-button type="primary" class="management-btn btn" style="margin-bottom: 15px" @click="handleDelete(scope)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handlePutaway">取 消</el-button>
        <el-button type="primary" @click="handlePutaway">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import Step from '@/components/step'
import Carousel from '@/components/carousel'
import Cover from '@/components/cover'
import { getTagList, getEditType, addTag, editTag, deleteTag, deleteAllTag } from '@/api/combo'
import { mapGetters } from 'vuex'
export default {
  name: 'One',
  components: {
    Step,
    Carousel,
    Cover
  },
  props: {
    infoDate: {
      type: Object,
      default() {
        return {}
      }
    },
    path: {
      type: String,
      default: ''
    },
    type: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      info: {
        package_name: '',
        package_intro: '',
        package_list_pic: '',
        package_pics: [],
        package_price: '',
        market_price: '',
        stock_quantity: 0,
        seller_sort: 0,
        desc: '',
        tag_id: ''
      },
      options: [],
      putawayDialog: false,
      selectItem: [],
      ratio: '1080*605',
      coverRatio: '314*230'
    }
  },
  computed: {
    tableData() {
      return this.options.map((item) => {
        item = Object.assign({}, item, { edit: false })
        return item
      })
    },
    ...mapGetters(['roles'])
  },
  async created() {
    const { edit } = this.$route.query
    await this.getTag()
    if (edit) {
      await this.getEdit()
    }
  },
  methods: {
    handleCoverChange(pic) {
      this.info.package_list_pic = pic
    },
    handleChangeCarousel(pics) {
      this.info.package_pics = pics
    },
    handleNext() {
      const { info } = this
      const flag = this.validity()
      if (flag) {
        if (typeof info.tag_id === 'string' && info.tag_id.toString().trim() !== '') {
          const index = this.options.findIndex((item) => {
            return item.tag_name === info.tag_id
          })
          this.info.tag_id = index > -1 ? this.options[index].id : 0
        }
        if (this.type === 'scenic') {
          console.log(info)
          this.info.package_pics = [require('../../assets/avatar.png')]
        }
        this.$router.push({
          path: this.path,
          query: {
            info: JSON.stringify({
              ...this.info,
              type: this.type
            })
          }
        })
      }
    },
    //  验证
    validity() {
      const { info, type } = this
      if (info.package_name.trim() === '') {
        this.$message.warning({
          message: '请输入正确的名称'
        })
        return false
      }
      if (!info.package_list_pic.length) {
        this.$message.warning({
          message: '请选择封面图片'
        })
        return false
      }
      if (!info.package_pics.length && type !== 'scenic') {
        this.$message.warning({
          message: '请选择轮播图片'
        })
        return false
      }
      if (info.package_price.trim() === '') {
        this.$message.warning({
          message: '请输入套餐价格'
        })
        return false
      }
      // if (Number(info.tag_id) === 0) {
      //   this.$message.warning({
      //     message: '请选择标签'
      //   })
      //   return false
      // }
      return true
    },
    handlePutaway() {
      this.deleteEmpty()
      this.putawayDialog = false
    },
    async getTag() {
      const res = await getTagList()
      const { lists } = res.data
      this.options = lists
    },
    async getEdit() {
      const { packageId } = this.$route.query
      const res = await getEditType({ type: this.type, package_id: packageId })
      const { item } = res.data
      if (!item) { this.$router.back() }
      const packAge = res.data.package
      const index = this.options.findIndex((item) => {
        return item.id === packAge.tag_id
      })
      packAge.tag_id = index > -1 ? this.options[index].tag_name : ''
      this.info = Object.assign({}, item, packAge)
    },
    cancelEdit(params) {
      const { tag_name, id } = params.row
      const index = params.$index
      if (tag_name.trim() === '' && !id) {
        this.tableData.splice(index, 1)
      } else {
        params.row.edit = false
      }
    },
    async confirmEdit(params) {
      const { tag_name, id } = params
      console.log(tag_name.trim())
      if (tag_name.trim() === '') {
        this.$message.warning({ message: '标签名不能为空', duration: 1000 })
        return
      }
      const index = this.options.findIndex((item) => {
        return item.tag_name === tag_name
      })
      if (index > -1) {
        this.$message.warning({ message: '标签名不能重复', duration: 1000 })
        return
      } else {
        if (id) {
          await editTag({ tag_id: id, tag_name })
          this.$message.success({
            message: '添加成功',
            duration: 1000
          })
          this.deleteEmpty()
          this.getTagAgain()
        } else {
          await addTag({ tag_name })
          this.$message.success({
            message: '修改成功',
            duration: 1000
          })
          this.deleteEmpty()
          this.getTagAgain()
        }
      }
    },
    handleAddTag() {
      if (this.tableData.length < 4) {
        this.tableData.push({
          tag_name: '',
          edit: true
        })
      } else {
        this.$message.warning({
          message: '标签不能多于四个',
          duration: 1000
        })
      }
    },
    deleteEmpty() {
      const result = []
      this.tableData.map((item) => {
        if (item.tag_name.trim() !== '') {
          result.push(item)
        }
      })
      return result
    },
    getTagAgain() {
      this.getTag()
      this.putawayDialog = false
    },
    // 批量删除
    handleSelectionChange(val) {
      this.selectItem = val
    },
    async handleDelete(scope) {
      const { id } = scope.row
      const index = scope.$index
      await deleteTag({ tag_id: id })
      this.$message.success({
        message: '删除成功',
        duration: 1000
      })
      this.tableData.splice(index, 1)
      this.options.splice(index, 1)
      const index1 = this.options.findIndex((item) => {
        return item.id === this.info.tag_id
      })
      this.info.tag_id = index1 > -1 ? this.options[index1].tag_name : ''
    },
    async handleDeleteAll() {
      if (!this.selectItem.length) {
        this.$message.warning({
          message: '请选择删除项',
          duration: 1000
        })
        return
      }
      let result = []
      this.selectItem.map((item) => {
        result.push(item.id)
      })
      result = result.join(',')
      await deleteAllTag({ result })
      this.$message.warning({
        message: '请选择删除项',
        duration: 1000
      })
      this.getTag()
    }
  }
}
</script>
<style lang="scss" scoped>
.one-wrap {
  width: 100%;
  background-color: #fff;
  .item-container{
    width: 100%;
    display: flex;
    align-items: center;
    margin-bottom: 15px;
    .title-wrap{
      display: flex;
      width: 100px;
      position: relative;
      .custom-class{
        width: 10px;
        height: 10px;
        position: absolute;
        top: 50%;
        transform: translateY(-50%);
        left: -15px;
      }
    }
    .title {
      font-size: 14px;
      line-height: 30px;
      width: 100px;
    }
    .management-btn{
      margin-left: 15px;
    }
    .input-container{
      width: 400px;
    }
    .textarea-container{
      width: 40%;
    }
  }
  .btn{
    margin-bottom: 16px;
  }
}
</style>
